import Vue from "vue";
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        list: JSON.parse(localStorage.getItem("todolist")) || [],
        getSel: "all",
    },
    mutations: {
        //添加功能
        addFn(state, name) {
            const id = state.list.length === 0 ? 1 : state.list[state.list.length - 1].id + 1;
            if (name.length === 0) return alert('输入的内容不能为空')
            state.list.push({
                id,
                name,
                isDone: false
            })

        },
        //删除功能
        delFn(state, id) {
            if (window.confirm("确定要删除吗？")) {
                // console.log(id);
                //根据id获取数组里的索引号
                const index = state.list.findIndex((obj) => obj.id === id);
                console.log(index);
                //调用splice()方法删除对应索引号的数据
                state.list.splice(index, 1);
            }
        },
        //切换(分类显示)
        typestr(state, isSel) {
            state.getSel = isSel;
        },
        //清空已完成
        clearFun(state) {
            state.list = state.list.filter((obj) => obj.isDone === false
            );
            localStorage.setItem(
                "todolist",
                JSON.stringify(state.list)
            );
        }
    },
    getters: {
        showType(state) {
            if (state.getSel === 'yes') {
                return state.list.filter((obj) => obj.isDone === true)
            } else if (state.getSel === 'no') {
                return state.list.filter((obj) => obj.isDone === false)
            } else {
                return state.list
            }
        }
    }
})



export default store